<template>
  <div class="c-bg-sgray">
    <div class="c-text-hidden cashBackBg c-pb160" v-if="isActEnd == false">
      <div class="c-ph24 c-pt70 c-p">
        <div class="c-w100">
          <div class="c-fs32 c-fc-white c-lh42 c-textAlign-c c-mb20">
            以下商品<template v-if="contents && contents.length == 1">{{cashBackTxt(contents[0], 1)}}</template>
            <template v-else-if="contents && contents.length > 1 && mostDiscount.isDiscount == 1">最高{{mostDiscount.detail.amount}}{{mostDiscount.isFreeShipping==1 || mostDiscount.isSendDiscount==1 || mostDiscount.isSendPoints==1 || mostDiscount.isSendProd==1 ? '且享优惠' : ''}}</template>
            <template v-else-if="contents && contents.length > 1 && mostDiscount.isDiscount == -1 && (mostDiscount.isFreeShipping==1 || mostDiscount.isSendDiscount==1 || mostDiscount.isSendPoints==1 || mostDiscount.isSendProd==1)">享满减送优惠</template>
          </div>
          <div class="c-flex-row c-aligni-center c-justify-center c-flexw-wrap" v-if="contents && contents.length > 1">
            <div v-for="(item, index) in contents" :key="index">
              <div v-if="item.isDiscount == 1 && item.detail" class="c-fs20 c-fc-white c-mr16 c-ph8 c-pv2 c-bd1-white c-br4 c-mb20">
                {{item.detail.title}}{{item.detail.amount}}
              </div>
            </div>
          </div>
        </div>
        <div class="c-fs20 c-fc-white c-flex-row c-flex-center c-pa c-p-r24 c-p-t24" @click="showRule = true">
          <i class="iconfont c-fs16 c-fc-white c-mr6">&#xe715;</i><span class="c-lh24">活动规则</span>
        </div>
        <div class="c-br8 c-bg-white c-text-hidden">
          <div class="c-fs24 c-fc-orange c-pv24 c-flex-row c-aligni-center c-justify-center c-mb1 c-ph24 c-bd-b1-f57a" v-if="formateTime">
            <span class="c-mr12 c-fc-xblack">距离活动结束仅剩</span>
            <span class="cellWidth c-lh c-pv5 c-textAlign-c c-bg-mb1-orange c-fc-white c-br2 ">{{formateTime.day}}</span>
            <span class="c-ph12 c-fw-b c-fs20">天</span>
            <span class="c-ww34 c-lh c-pv5 c-textAlign-c c-bg-mb1-orange c-fc-white c-br2 ">{{formateTime.hour}}</span>
            <span class="c-ph12 c-fw-b c-fs20">:</span>
            <span class="c-ww34 c-lh c-pv5 c-textAlign-c c-bg-mb1-orange c-fc-white c-br2">{{formateTime.minute}}</span>
            <span class="c-ph12 c-fw-b c-fs20">:</span>
            <span class="c-ww34 c-lh c-pv5 c-textAlign-c c-bg-mb1-orange c-fc-white c-br2">{{formateTime.second}}</span>
          </div>
          <div v-if="shopList.length > 0" class="c-bg-white c-ph24">
            <div v-for="(item, index) in shopList" :key="index" class="c-flex-row c-justify-sb c-pv20" :class="index == (shopList.length - 1) ? '' : 'c-bd-b1-f2'">
              <div class="c-ww120 c-maxh120 c-text-hidden c-p c-br4" @click="goShopDetail(item.mgId)">
                <img :src="$addXossFilter(item.avatar, require('@/assets/defult270.png'))" class="c-br4">
                <div class="c-fs20 c-pa c-translucent-balck30 c-w100 c-h c-flex-row c-flex-center c-p-t0 c-p-l0" v-if="item.stock == 0"><span class="c-fc-white">已售罄</span></div>
              </div>
              <div class="c-w0 c-flex-grow1 c-flex-column c-justify-sb c-ml20">
                <div class="c-fs24 c-fc-xblack c-text-ellipsis1">{{item.name}}</div>
                <div class="c-flex-row c-aligni-center c-justify-sb">
                  <div class="c-fs24" :class="item.stock > 0 ? 'c-fc-xmlred' : 'c-fc-gray'">{{'￥' | iosPriceFilter}}{{item.price}}</div>
                  <div class="iconfont c-fc-gray c-fs30" v-if="item.stock > 0" @click="onShowSpecifications(item.mgId, item.mcId, index)">&#xe722;</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-modal">
      <div class="c-bg-spink c-fc-xblack c-flex-row c-aligni-center c-pl24 c-fs22 c-pv20" v-if="contents.some(item => item.isSendProd == 1 && item.sendProdList.length > 0)">购买活动商品满足条件后即可获得赠品，<span class="c-fc-orange" @click="showAllSendProdList = true">查看赠品</span></div>
      <div class="c-bg-white c-bd-t1 c-flex-row c-aligni-center c-justify-sb c-ph24 c-pv15">
        <div class="c-flex-column">
          <div class="c-flex-row">
            <span class="c-fs24 c-fc-xblack">小计：</span>
            <span class="c-fs24 c-fc-orange"><span>{{'￥' | iosPriceFilter}}</span>{{totalPrice}}</span>
          </div>
          <span class="c-fs20 c-fc-sblack">
            <template v-if="totalPrice > 0">
              <template v-if="useMcbgId > -1 && currentMcb">
                {{currentMcb.isDiscount == 1 ? '可' + (currentMcb.discountType == 1 ? '立' : '享') + cashBackTxt(currentMcb, 3) : '可享活动优惠'}}
              </template>
              <template v-else>{{getActivityTxt}}</template>
            </template>
            <template v-else>赶紧选购商品参与促销活动吧</template>
          </span>
        </div>
        <div class="c-fs24 c-ww176 c-textAlign-c c-linebg-orange c-fc-white c-br36 c-ml24 c-pv16" @click="goShopCart">去购物车</div>
      </div>
    </div>

    <!-- 赠品 -->
    <open-modal :openModal='showAllSendProdList' @closeModal='showAllSendProdList = false'>
      <div class="masker-content c-br-tl20 c-br-tr20">
        <div class="c-p">
          <div class="c-w100 c-textAlign-c c-fs28 c-pt24 c-fc-sblack">赠品</div>
          <i class="iconfont c-pa c-p-t24 c-p-r24 c-fc-sgray c-fs20 c-bg-f6 c-ww30 c-hh30 c-brp50 c-flex-row c-flex-center" @click="showAllSendProdList = false">&#xe8fd;</i>
          <div class="c-pt40 c-ph24 c-pb60">
            <div class="c-maxh544">
              <div v-for="(item, index) in allSendProdList" :key="index" class="c-flex-row c-justify-sb c-pv20 c-bd-b1-f2">
                <div class="c-ww120 c-maxh120 c-text-hidden">
                  <img :src="$addXossFilter(item.cover, require('@/assets/defult270.png'))">
                </div>
                <div class="c-w0 c-flex-grow1 c-flex-column c-ml20">
                  <div class="c-fs24 c-fc-xblack">{{item.name}}</div>
                  <div class="c-mt14 c-flex-row c-flexw-wrap">
                    <span v-for="(cItem, cIndex) in contents" :key="cIndex" class="c-flex-row c-aligni-center">
                      <span v-if="cItem.isSendProd == 1 && cItem.sendProdList.filter(it => it.prodId == item.prodId).length > 0 && cItem.detail" class="c-mb14 c-fc-lorange c-br2 tagBg c-pv2 c-ph4 c-fs18 c-mr12">
                        {{cItem.detail.title}}赠送
                      </span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </open-modal>

    <!-- 活动规则 -->
    <open-modal :openModal='showRule' @closeModal='showRule = false'>
      <div class="masker-content c-br-tl20 c-br-tr20">
        <div class="c-p">
          <div class="c-w100 c-textAlign-c c-fs28 c-pt24 c-fc-sblack">活动规则</div>
          <i class="iconfont c-pa c-p-t24 c-p-r24 c-fc-sgray c-fs20 c-bg-f6 c-ww30 c-hh30 c-brp50 c-flex-row c-flex-center" @click="showRule = false">&#xe8fd;</i>
          <div class="c-pt40 c-pb40 c-ph24">
            <div class="content-scroll">
              <div class="c-fs24 c-fc-gray">活动时间</div>
              <div class="c-fs24 c-fc-xblack c-mt12">{{startTime.replace(/-/g, '.')}} 至 {{endTime.replace(/-/g, '.')}}</div>
              <div class="c-fs24 c-fc-gray c-mt40">活动内容</div>
              <div class="c-mt16 c-flex-row c-aligni-start" v-if="!(contents.every(item => {return item.isDiscount == -1}))">
                <div class="c-br4 c-tibg c-inlineblack c-fs18 c-lh20 c-fc-xmlred c-textAlign-c c-ph4 c-pv2 c-ww52 c-mt5">满减</div>
                <div class="c-flex-row c-flexw-wrap c-aligni-start c-h c-w0 c-flex-grow1">
                  <span v-for="(item, index) in contents" :key="index" class="c-flex-row c-flex-center">
                    <span v-if="item.isDiscount == 1 && item.detail" class="c-fs24 c-fc-xblack c-ml26 c-mb2">
                      {{item.detail.title}}{{item.detail.amount}}
                    </span>
                  </span>
                </div>
              </div>
              <div class="c-mt16 c-flex-row c-aligni-start" v-if="contents.some(item => item.isSendPoints == 1 || item.isSendDiscount == 1 || item.isSendProd == 1)">
                <div class="c-br4 c-tibg c-inlineblack c-fs18 c-lh20 c-fc-xmlred c-textAlign-c c-ph4 c-pv2 c-ww52 c-mt5">满赠</div>
                <div class="c-flex-row c-flexw-wrap c-aligni-start c-h c-w0 c-flex-grow1">
                  <div v-for="(item, index) in contents.filter(item => {return item.isSendPoints == 1 || item.isSendDiscount == 1 || item.isSendProd == 1})" :key="index" class="c-fs24 c-fc-xblack c-ml26 c-mb2 c-lh34 c-w100">
                    {{item.detail.title}}，
                    <span v-for="(it, i) in item.sendProdList" :key="i">
                      送{{it.number}}件<span class="c-ph20 c-fc-xmlred" @click="goShopDetail(it.prodId)">{{it.prodName}}</span>{{i == (item.sendProdList.length - 1) ? '' : '、'}}
                    </span>{{cashBackTxt(item, 7)}}
                  </div>
                </div>
              </div>
              <div class="c-mt12 c-flex-row c-aligni-start" v-if="contents.filter(item => {return item.isFreeShipping == 1}).length > 0">
                <div class="c-br4 c-tibg c-inlineblack c-fs18 c-lh20 c-fc-xmlred c-textAlign-c c-ph4 c-pv2 c-ww52 c-mt5">包邮</div>
                <div class="c-flex-row c-flexw-wrap c-aligni-start c-h c-w0 c-flex-grow1">
                  <div v-for="(item, index) in contents.filter(mItem => {return mItem.isFreeShipping == 1})" :key="index" class="c-fs24 c-fc-xblack c-ml26 c-mb2">
                    {{item.detail.title}}{{item.detail.ship}}
                  </div>
                </div>
              </div>
              <div class="c-fs22 c-fc-gray c-mt16">注意：该活动不可与其他优惠活动同时使用</div>
            </div>
          </div>
        </div>
      </div>
    </open-modal>

    <!-- 规格弹窗 -->
    <open-modal :openModal='showSpecifications' @closeModal='closeSpecModal'>
      <div class="masker-specifications-content c-flex-column c-br-tl20 c-br-tr20">
        <div class="c-ph24 c-flex-column c-flex-grow1">
          <div class="c-flex-row c-pt24 c-pb40">
            <div class="masker-content-img c-text-hidden c-br10" v-if="shopInfo != null">
              <img class="c-w100 c-br10" :src="$addXossFilter(shopInfo.avatar, require('@/assets/defult270.png'))" alt="" />
            </div>
            <div class="c-pl20 c-fs24 c-flex-grow1 c-w0" v-if="shopInfo != null">
              <div class="c-lh">
                <span class="c-fs40">{{'￥' | iosPriceFilter}}{{currentSpecItemInfos != null ? currentSpecItemInfos.price : shopInfo.price}}</span>
              </div>
              <div class="c-lh c-pt10 c-flex-row c-fc-gray c-fs20 c-justify-sb">
                <span class="c-flex-grow1 c-w0 c-text-decoration-through" v-if="(currentSpecItemInfos != null && currentSpecItemInfos.originalPrice) || (shopInfo && shopInfo.originalPrice)">{{'￥' | iosPriceFilter}}{{currentSpecItemInfos != null && currentSpecItemInfos.originalPrice ?currentSpecItemInfos.originalPrice:shopInfo.originalPrice}}</span>
                <span>库存：{{currentSpecItemInfos != null?currentSpecItemInfos.stock:shopInfo.stock}}件</span>
              </div>
            </div>
            <div class="iconfont c-fc-gray c-fs32" @click="closeSpecModal">&#xe6e1;</div>
          </div>
          <div class="c-flex-grow1 c-h0 c-contexty-auto">
            <div class="c-pb30" v-for="(item,index) in specsList" :key="index">
              <div class="c-fs22 c-fc-xblack c-fw-b">{{item.name}}</div>
              <div class="c-flex-row c-flexw-wrap">
                <div
                  :class="[((isChangeSelectType == true && childItem.gsiId == currentDefaltSpec[index]) || (isChangeSelectType == false && childItem.gsiId == currentDefaltSpec[index])) && childItem.noSelect != true ? 'c-fc-orange c-bd1-orange':' c-fc-xblack',childItem.noSelect == true ? 'c-fc-gray c-text-decoration-through' : '']"
                  @click="chooseSpecsItem(index, childItem.gsiId, childItem.noSelect)"
                  class="c-flex-row c-flex-center c-fs22 c-ph30 c-pv12 c-br28 c-mt30 c-mr20 c-bg-f6"
                  v-for="(childItem, childIndex) in specItems" v-if="item.gsId == childItem.gsId" :key="childIndex">{{childItem.name}}
                </div>
              </div>
            </div>
            <div class="c-flex-row c-pt10 c-justify-sb c-aligni-center" v-if="shopInfo && currentSpecItemInfos">
              <div class="c-flex-grow1 c-w0 c-fs26 c-fw-b">数量
              </div>
              <div class="c-flex-row c-aligni-center">
                <div class="theme-fc c-fs22 c-mr24" v-if="shopInfo.limitType != -1">
                  ({{shopInfo.limitType == 1 ? '' : limitCycleTypeMap[shopInfo.limitCycleType]}}限购{{shopInfo.limitNumber}}件)
                </div>
                <shop-number
                  :max='shopInfo && shopInfo.limitType != -1 ? (shopInfo.limitNumber - shopInfo.purchasedNum) : currentSpecItemInfos.stock'
                  :min='shopInfo.minOrderQuantity'
                  :inputNum='currentInputNum'
                  :isLimitBuy='shopInfo.limitType'
                  :limitNumber='shopInfo.limitNumber'
                  :purchasedNum='shopInfo.purchasedNum'
                  @outMaxNum='isShowLimitToast'
                  @subNum='subNum'
                  @addNum='addNum'
                  @inputChange='inputChange'
                ></shop-number>
              </div>
            </div>
          </div>
        </div>
        <div class="c-pt20 c-flex-row c-ml24 c-mr24">
          <div class="c-fs24 c-fc-white c-br36 c-lh34 c-pv16 c-linebg-orange c-textAlign-c c-w100 c-mb20" @click="joinCart()">确定</div>
        </div>
      </div>
    </open-modal>
    <div v-if="isActEnd">
      <loading-status-tem :noData='true' noDataText="活动结束"></loading-status-tem>
      <div class="c-bg-white c-bd1-orange c-fs24 c-pv16 c-br36 c-ww240 c-center c-fc-orange c-textAlign-c" @click="goMallIndex">查看其它商品</div>
    </div>
  </div>
</template>

<script>
import ShopNumber from "@/components/templates/shopNumber.vue";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import OpenModal from "@/components/templates/common/openModal.vue";
import { utilJs } from "@/utils/common.js";
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";
let gsiIds = [] // 二级规格id组合
let allGsiIds = [] // 所有规格值id
const LIMIT = 20;
let page = 1;
let timeControl;
let countDownTime = 0;
let currentDate = ""; // 系统时间
let amount = 0; // 满减合计
export default {
  name: "CashBackActivity",
  components: {
    ShopNumber,
    OpenModal,
    loadingStatusTem
  },
  props: [],
  data() {
    return {
      customPointName: localStorage.getItem("customPointName"),
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      dataStatus: 'HAS_MORE_DATA',
      totalPrice: 0.0,
      shopList: [], // 满减商品列表
      shopInfo: null, // 商品信息
      specsList: [], // 选中商品大类列表
      specItems: [], // 选中商品小类列表
      specItemInfos: [], // 每个商品的规格信息
      shopIndex: -1, // 目前商品的索引
      currentInputNum: 1,
      currentDefaltSpec: [0, 0], // 最低价格标识，且有库存
      currentSpecItemInfos: null, // 当前选中规格
      isChangeSelectType: false, // 判断规格是否改变
      formateTime: '', // 活动时间格式
      showRule: false, // 展示活动规则
      shopBuyInfo: [], // 购买的信息
      contents: [], // 优惠信息
      mostDiscount: null,
      useMcbgId: -1, // 使用的满减id
      currentMcb: null, // 使用的满减优惠信息
      mcbId: '14', // 满减id
      ruleType: 1, // 1阶级满减 2循环满减
      title: null, // 活动标题
      shareDesc: null, // 活动描述
      startTime: '',
      endTime: '',
      cartNum: 0, // 购物车商品件数
      isActEnd: false, // 活动是否结束
      limitCycleTypeMap: {
        '1': '每天',
        '2': '每周',
        '3': '每月',
      },
      allSendProdList: [], // 该活动赠送的商品合集
      showAllSendProdList: false, // 展示全部赠品的列表
      bindPhoneSetting: null
    };
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {
    // 再买X元/件，可减X员/打X折，包邮(未达到门槛的展示文字)
    getActivityTxt() {
      let cashBack = this.getcashBack(this.shopBuyInfo, this.contents, this.ruleType);
      // 判断是否是最高级的优惠 阶梯获取最高级 循环获取单级优惠
      let isMost = this.ruleType == 1 ? (this.currentMcb ? this.contents.filter(item => {return this.currentMcb.grade <= item.grade}) : this.contents) : (this.ruleType == 2 ? this.contents : []);
      let nextGrade = isMost[0];
      let grap = this.ruleType == 1 ?
        (nextGrade.backType == 1 ? nextGrade.thresholdAmount - cashBack.price : nextGrade.thresholdAmount - cashBack.cartNum) :
        (nextGrade.backType == 1 ? nextGrade.thresholdAmount * (cashBack.loop + 1) - cashBack.price : nextGrade.thresholdAmount * (cashBack.loop + 1) - cashBack.cartNum);
      let txt = this.ruleType == 1 ?
        (`再买${nextGrade.backType == 1 ? grap + '元' : grap + '件'}${nextGrade.isDiscount == 1 ? '，可' + (nextGrade.discountType == 2 ? '打' + (nextGrade.backDiscount * 1 / 10) + '折' : '减' + nextGrade.backAmount + '元') : ''}${nextGrade.isFreeShipping == 1 ? '，包邮' : ''}`) :
        (`再买${nextGrade.backType == 1 ? grap + '元' : grap + '件'}，可满${nextGrade.thresholdAmount * (cashBack.loop + 1)}${nextGrade.backType == 1 ? '元' : '件'}${nextGrade.isDiscount == 1 ? '减' + nextGrade.backAmount * (cashBack.loop + 1) + '元' : ''}${nextGrade.isFreeShipping == 1 ? '，包邮' : ''}`)
      return `${txt}`;
    },
    // 满 * 元/件 减/打 * 元/折
    cashBackTxt() {
      return function(discountInfo, type) {
        if (type == 1) { // 满xx元/件减/打xx元/折
          let txt = discountInfo.detail.title + discountInfo.detail.amount;
          let endTxt = '';
          if (discountInfo.isDiscount == 1 && (discountInfo.isFreeShipping == 1 || discountInfo.isSendDiscount == 1 || discountInfo.isSendProd == 1 || discountInfo.isSendPoints == 1)) {
            endTxt = '且享优惠'
            return txt + endTxt
          } else if (discountInfo.isDiscount == -1) {
            if (discountInfo.isFreeShipping == 1 && discountInfo.isSendDiscount == -1 && discountInfo.isSendProd == -1 && discountInfo.isSendPoints == -1) {
              endTxt = '包邮' // 无价格优惠仅有包邮
              return txt + endTxt
            } else {
              endTxt = '享满减送优惠' // 无价格优惠/包邮/赠送
              return endTxt
            }
          }
        } else if (type == 3) { // 计算添加购物车商品活动力度
          if (this.ruleType == 1) {
            return discountInfo.detail.amount;
          } else {
            let cashBack = this.getcashBack(this.shopBuyInfo, this.contents, this.ruleType);
            let loop = cashBack ? cashBack.loop : 1;
            return '减' + discountInfo.backAmount * loop + '元';
          }
        } else if (type == 7) { // 显示"、送x张无门槛券、x张折扣券、送x积分"
          let sendDiscount = '';
          let sendPoints = '';
          if (discountInfo.isSendDiscount == 1) {
            sendDiscount = `${discountInfo.isSendProd == 1 ? '、' : ''}送`
            discountInfo.sendDiscountList .forEach((item, index) => {
               sendDiscount = `${sendDiscount}${item.number}张${item.redeemCodeType == 1 ? '兑换码' : (item.redeemCodeType == 2 ? '代金券' : (item.redeemCodeType == 3 ? '满减券' : (item.redeemCodeType == 4 ? '抵价券' : '折扣券')))}${index == (discountInfo.sendDiscountList.length - 1) ? '' : '、'}`
            })
          }
          if (discountInfo.isSendPoints == 1) {
            sendPoints = `${discountInfo.isSendDiscount == 1 || discountInfo.isSendProd == 1 ? '、' : ''}送${discountInfo.points}${this.customPointName}`;
          }
          return sendDiscount + sendPoints;
        }
      }
    }
  },
  mounted() { },
  watch: {
    //监听购物车列表数据变化，自动计算总价格
    shopBuyInfo: {
      handler(newList, oldList) {
        // 计算选中的商品的总价格
        this.totalPrice = utilJs.toMyFixed2(newList.reduce((price, item) => {
          return price + (item.price * 1) * item.quantity;
        }, amount));
        let cartNum = newList.reduce((quantity, item) => {
          return quantity + item.quantity;
        }, this.cartNum);
        this.getUseMcbgId(cartNum);
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 数组去重, 按照商品id去重
    getUnique(arr) {
      let map = {};
      arr.forEach(item => map[JSON.stringify(item.prodId)] = item); // 1、把数组元素作为对象的键存起来（这样就算有重复的元素，也会相互替换掉）
      return Object.keys(map).map(key => map[key]) // 2、再把对象的值抽成一个数组返回即为不重复的集合
    },
    // 获取当前符合满减条件信息
    getUseMcbgId(total) {
      for (let item of this.contents) {
        if (((this.totalPrice >= item.thresholdAmount) && item.backType == 1) || ((total >= item.thresholdAmount) && item.backType == 2)) {
          this.useMcbgId = item.mcbgId;
          this.currentMcb = this.contents.filter(item => {return this.useMcbgId == item.mcbgId})[0];
        }
      }
    },
    // 计算满减优惠券
    getcashBack(products, contents, type) {
      let actPrice = products.reduce((mPrice, mItem) => { // 商品加入购物车的金额
        return mPrice + (mItem.price * 1) * mItem.quantity;
      }, amount);
      let loop = 0;
      let cartNum = products.reduce((quantity, item) => {
        return quantity + item.quantity;
      }, this.cartNum);
      // 阶级满减
      if (type == 1) {
        if (this.useMcbgId > -1) {
          actPrice = this.currentMcb.isDiscount == 1 ? (this.currentMcb.backType == 1 ? (actPrice - this.currentMcb.backAmount) : ((this.currentMcb.backDiscount * 1 / 100) * actPrice)) : 0;
        }
        return {price: actPrice, cartNum: cartNum}
      // 循环满减 (只有金额累加满减无打折满减)
      } else {
        loop = contents[0].backType == 1 ? Math.floor(actPrice / contents[0].thresholdAmount) : Math.floor(cartNum / contents[0].thresholdAmount);
        actPrice = actPrice - (contents[0].backAmount * loop);
        return {price: actPrice, loop: loop, cartNum: cartNum}
      }
    },
    // 设置标签无库存
    changeChildTypeList(gsiId, status) {
      for (let i = 0; i < this.specItems.length; i++) {
        let item = this.specItems[i];
        if (item.gsiId == gsiId) {
          if (status == 0) {
            this.$set(this.specItems[i], 'noSelect', true);
          } else {
            this.$set(this.specItems[i], 'noSelect', false);
          }
        }
      }
    },
    // 获取一级分类组合
    getItemGroupMap() {
      let itemGroupMap = [];
      for (let i = 0; i < this.specItemInfos.length; i++) {
        let item = this.specItemInfos[i];
        let arr = JSON.parse(item.itemGroup);
        if (!itemGroupMap[arr[0]]) {
          itemGroupMap[arr[0]] = {
            number: arr[0],
            items: [item]
          };
        } else {
          itemGroupMap[arr[0]].items.push(item);
        }
      }
      return itemGroupMap;
    },
    // 库存0 判断
    checkStockNull() {
      this.isChangeSelectType = false;
      if (this.specItemInfos && this.specItemInfos.length > 0) {
        let itemGroupMap = this.getItemGroupMap();
        let keys = Object.keys(itemGroupMap);
        let items = [];
        // 判断一级
        for (let i = 0; i < keys.length; i++) {
          items = itemGroupMap[keys[i]].items;
          let allNull = items.every(single => single.stock == 0);
          if (allNull) {
            this.changeChildTypeList(itemGroupMap[keys[i]].number, 0);
          }
        }
        // 初始选择第二级规格判断
        if (this.currentDefaltSpec.length > 1) {
          let aItems = itemGroupMap[this.currentDefaltSpec[0]].items;
          for (let i = 0; i < aItems.length; i++) {
            let item = aItems[i];
            let array = JSON.parse(item.itemGroup);
            if (item.stock == 0) {
              this.changeChildTypeList(array[1], 0);
            }
          }
        }
      }
    },
    //递归判断库存是否为0
    checkStock(gsiId) {
      let gsiIdIndex = allGsiIds.indexOf(gsiId);
      let itemGroup = '[' + this.currentDefaltSpec + ']';
      let gsId = this.specsList[1].gsId;
      let gsiIdArr = this.specItems.filter((item) => {
        return item.gsId == gsId;
      })
      gsiIdArr.forEach((item) => {
        gsiIds.push(item.gsiId);
      })
      let first = gsiIds[0];
      let last = gsiIds.pop();
      let checkNull = this.specItemInfos.filter((item) => {
        return item.itemGroup == itemGroup && item.stock == 0;
      })
      if (checkNull.length == 0) {
        return;
      }
      if (gsiId == last) {
        this.$set(this.currentDefaltSpec, 1, first);
        this.checkStock(first);
      } else {
        this.$set(this.currentDefaltSpec, 1, allGsiIds[gsiIdIndex + 1]);
        this.checkStock(allGsiIds[gsiIdIndex + 1]);
      }
    },
    // 选择商品分类
    chooseSpecsItem(index, childGsid, status) {
      if (status) {
        return;
      }
      for (let i = 0; i < this.specItems.length; i++) {
        let item = this.specItems[i];
        if (item.gsiId == childGsid) {
          this.$set(this.currentDefaltSpec, index, childGsid);
          // 一级规格切换 修改库存0标识
          if (index == 0) {
            let itemGroupMap = this.getItemGroupMap();
            let items = itemGroupMap[childGsid].items;
            for (let a = 0; a < items.length; a++) {
              let aItem = items[a];
              let array = JSON.parse(aItem.itemGroup);
              if (aItem.stock == 0) {
                this.changeChildTypeList(array[1], 0);
              } else {
                this.changeChildTypeList(array[1], 1);
              }
            }
          }
          if (this.currentDefaltSpec[1]) {
            this.checkStock(this.currentDefaltSpec[1]);
          }
          this.isChangeSelectType = true;
        }
      }
      this.initCurrentSpecItemInfos(JSON.stringify(this.currentDefaltSpec), this.specItemInfos);
    },
    // 展示商品规格选择弹窗
    onShowSpecifications(mgId, mcId, index) {
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind) {
        if (utilJs.goBindMobile()) return;
      }
      this.shopIndex = index;
      this.specsList = [];
      this.specItems = [];
      this.specItemInfos = [];
      this.shopIndex = -1;
      this.currentInputNum = 1;
      this.currentDefaltSpec = [0, 0];
      this.currentSpecItemInfos = null;
      this.isChangeSelectType = false;
      gsiIds = [];
      allGsiIds = [];
      this.getShopInfo(mgId);
    },
    // 关闭规格弹窗
    closeSpecModal() {
      this.showSpecifications = false;
    },
    // 获取所选的规格信息
    initCurrentSpecItemInfos(speceArr, specItemInfos) {
      this.currentSpecItemInfos = this.specItemInfos.filter(i => i.itemGroup == speceArr)[0];
      if (this.currentSpecItemInfos == null) {
        this.currentSpecItemInfos = {
          gsiiId: null,
          itemGroup: null,
          mgId: this.shopInfo.mgId,
          price: this.shopInfo.price * 1,
          stock: this.shopInfo.stock
        }
      }
    },
    // 获取商品规格
    getShopInfo(mgId) {
      let that = this;
      utilJs.getMethod(
        global.apiurl + "goods/goodsDetail?mgId=" + mgId,
        res => {
          that.shopInfo = res.goods;
          that.specsList = res.specs;
          that.currentDefaltSpec = res.goods.defaltSpec ? res.goods.defaltSpec : [];
          that.specItems = res.specItems;
          that.specItemInfos = res.specItemInfos;
          that.showSpecifications = true;
          that.specItems.forEach(item => {allGsiIds.push(item.gsiId);})
          that.initCurrentSpecItemInfos(JSON.stringify(that.currentDefaltSpec), that.specItemInfos);
          that.checkStockNull();
        });
    },
    // 限购弹窗
    isShowLimitToast(limitNumber, purchasedNum, quantity) {
      if (limitNumber <= purchasedNum) {
        this.$showCjToast({
          text: '您已购买过该商品，当前不能购买更多了',
          type: "warn",
          time: 1500
        });
      } else if (limitNumber <= (purchasedNum + quantity)) {
        this.$showCjToast({
          text: '当前不能购买更多了',
          type: "warn",
          time: 1500
        });
      }
    },
    timeControl() {
      let that = this;
      timeControl = setInterval(function () {
        currentDate++;
        countDownTime--;
        if (countDownTime <= 0) {
          that.isActEnd = true;
          clearInterval(timeControl);
        }
        that.formateTime = that.timeToStr(countDownTime);
      }, 1000);
    },
    // 将秒转化为天/时/分/秒
    timeToStr(timeSecond) {
      if (timeSecond == 0) return
      let day = 0;
      let hour = 0;
      let minute = 0;
      let second = 0;
      if (timeSecond >= 60) {
        minute = parseInt(timeSecond / 60);
        second = parseInt(timeSecond % 60);
        if (minute >= 60) {
          hour = parseInt(minute / 60);
          minute = parseInt(minute % 60);
        } if (hour >= 24) {
          day = parseInt(hour / 24);
          hour = parseInt(hour % 24);
        }
      } else {
        second = timeSecond;
      }
      hour = hour >= 10 ? hour : "0" + hour;
      minute = minute >= 10 ? minute : "0" + minute;
      second = second >= 10 ? second : "0" + second;
      return {day: day, hour: hour, minute: minute, second: second};
    },
    // 加入购物车
    joinCart() {
      this.showSpecifications = false;
      if (this.currentSpecItemInfos && this.currentSpecItemInfos.stock * 1 < this.currentInputNum) {
        this.$showCjToast({
          text: "库存不足",
          type: "warn",
          time: 1500
        });
        return;
      }
      utilJs.postMethod(
        global.apiurl + "goods/addToCart",
        {
          mgId: this.shopInfo.mgId,
          quantity: this.currentInputNum || 1,
          gsiiId: this.currentSpecItemInfos ? this.currentSpecItemInfos.gsiiId : '',
          price: this.currentSpecItemInfos ? this.currentSpecItemInfos.price * 1 : this.shopInfo.price * 1
        },
        res => {
          let info = {
            mgId: this.shopInfo.mgId,
            price: this.currentSpecItemInfos ? this.currentSpecItemInfos.price * 1 : this.shopInfo.price * 1,
            quantity: this.currentInputNum,
            gsiiId: this.currentSpecItemInfos ? this.currentSpecItemInfos.gsiiId : null,
            stock: this.currentSpecItemInfos ? this.currentSpecItemInfos.stock : this.shopInfo.stock,
          }
          this.shopBuyInfo.push(info);
          this.$showCjToast({
            text: "商品已加入购物车",
            type: "success",
            time: 1500
          });
        }
      );
    },
    goMallIndex() {
      this.$routerGo(this, "push", {
        path: "/mall/classification/classificationAll"
      });
    },
    // 跳转到购物车
    goShopCart() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind) {
        if (utilJs.goBindMobile()) return;
      }
      this.$routerGo(this, "push", {
        path: "/mall/shopCart/shopCart",
        query: { mcbId: this.mcbId }
      });
    },
    // 跳转到商品详情
    goShopDetail(shopNo) {
      this.$routerGo(this, "push", {
        path: "/mall/shopDetail/shopDetail",
        query: { shopNo: shopNo }
      });
    },
    //数量增加
    addNum(item) {
      this.currentInputNum = item.inputNumber;
    },
    //数量减少
    subNum(item) {
      this.currentInputNum = item.inputNumber;
    },
    //输入数量
    inputChange(item) {
      this.currentInputNum = item.inputNumber;
    },
    // 获取满减详情
    getCashBackDetail() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(global.apiurl + "mallCashBack/getCashBackDetail?mcbId=" + this.mcbId + '&page=' + page + '&limit=' + LIMIT, res => {
        if (page == 1) {
          this.shopList = res.products.data;
          this.ruleType = res.ruleType;
          this.contents = res.contents;
          amount = res.amount * 1;
          this.totalPrice = amount > 0 ? amount : 0;
          this.shareDesc = res.shareDesc || null;
          this.title = res.title || null;
          this.cartNum = res.cartNum ? res.cartNum * 1 : 0;
          this.getUseMcbgId(this.cartNum);
          this.isSendPoints = res.isSendPoints;
          if (this.title) {
            setDocumentTitle(this.title); // eslint-disable-line
          } else {
            setDocumentTitle("满减送活动"); // eslint-disable-line
          }
          this.startTime = res.startTime;
          this.endTime = res.endTime;
          if (res.status == 3) { // 活动结束
            this.isActEnd = true;
          } else if (res.status == 2) {
            let end = this.endTime.replace(/-/g, '/'); // 兼容ios去Date.parse失效
            currentDate = res.time;
            countDownTime = (Date.parse(end) / 1000) - currentDate;
          }
          this.timeControl();
          if (this.contents && this.contents.length > 0) {
            this.mostDiscount = this.contents[0];
            if (this.ruleType == 1) {
              this.contents.forEach(item => {
                if (this.mostDiscount.grade < item.grade) {
                  this.mostDiscount = item;
                }
              })
            }
            let sendProdContent = this.contents.filter(item => item.isSendProd == 1);
            sendProdContent.forEach(item => {
              this.allSendProdList = [...this.allSendProdList, ...item.sendProdList]
            })
            this.allSendProdList = this.getUnique(this.allSendProdList);
          }
          this.wechatShare();
        } else {
          this.shopList = [...this.shopList, ...res.products.data];
        }
        if (res.products.next_page_url == null) {
          this.dataStatus = res.products.to == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          page++;
        }
        })
    },
    //分享
    wechatShare: function () {
      let title = '超值的满减/送活动进行中，赶紧来抢购吧！';
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/mall/cashBackActivity/cashBackActivity?mcbId=" + this.mcbId + '&refereeId=' +
        localStorage.getItem("userId");
      let shareDesc = this.shareDesc && this.shareDesc.length > 0 ? this.shareDesc : (this.title && this.title.length > 0 ? this.title : window.localStorage.getItem("shareDesc"));
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      var shareUrl =
        window.location.href.split("#")[0] +
        "#/mall/cashBackActivity/cashBackActivity?mcbId=" + this.mcbId + '&refereeId=' +
        localStorage.getItem("userId");
      utilJs.appShareTrue("", "", shareUrl, "");
    },
    windowScrollFunction: function () {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.shopList.length > 0) {
          this.getCashBackDetail();
        }
      });
    }
  },
  activated() {
    if (timeControl) clearInterval(timeControl);
    this.mcbId = this.$route.query.mcbId ? this.$route.query.mcbId : '';
    this.mostDiscount = null;
    this.useMcbgId = -1;
    this.specsList = [];
    this.specItems = [];
    this.specItemInfos = [];
    this.shopIndex = -1;
    this.currentInputNum = 1;
    this.currentDefaltSpec = [0, 0];
    this.currentSpecItemInfos = null;
    this.isChangeSelectType = false;
    this.contents = [];
    this.dataStatus = 'HAS_MORE_DATA';
    this.totalPrice = 0;
    this.cartNum = 0;
    this.isActEnd = false;
    this.shopList = [];
    this.currentMcb = null;
    this.shopBuyInfo = [];
    this.allSendProdList = [];
    amount = 0
    countDownTime = 0;
    page = 1;
    getBindPhoneSetting(global.ckFrom.shopping).then(res => {
      this.bindPhoneSetting = res;
    });
    this.getCashBackDetail();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<style scoped>
.masker-content {
  background-color: #fff;
  width: 100%;
  z-index: 1003;
}
.bottom-modal {
  width: 100%;
  max-width: 16rem;
  border: 1px solid rgba(242, 242, 242, 1);
  background-color: #ffffff;
  box-shadow: 0px -6px 3px 0px rgb(132 132 132 / 3%);
  position: fixed;
  margin: 0 auto;
  left: 0;
  right: 0;
  bottom: 0;
}
.masker-specifications-content {
  background-color: #fff;
  max-height: 16rem;
  height: 16rem;
  width: 100%;
}
.masker-content-img {
  width: 3.75rem;
  max-height: 3.75rem;
}
.cashBackBg {
  background-image: url('../../../assets/i/wap/mall/cashBackBg.png');
  background-repeat: no-repeat;
  background-position: center top;
  background-size: 100% 6rem;
}
.c-bd1-white {border: 1px solid #ffffff;}
.c-linebg-lorange {
  background: -webkit-linear-gradient(180deg, rgba(255,48,12,0.7), #FF300C)
}
.c-tibg{
  background: rgba(255,48,12,0.1);
}
.c-maxh544 {
  max-height: 13.6rem;
  overflow-y: auto;
}
.tagBg {
  background-color: rgba(255,48,12,0.1);
}
.c-fc-lorange {color: #FF300C;}
.c-bd-b1-f57a {
  border-bottom: 1px solid #F5F7FA;
}
.c-bd-b1-f2 {
  border-bottom: 1px solid #f2f2f2;
}
.content-scroll {
  height: 12rem;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.cellWidth {
  min-width: 0.85rem;
  width: auto;
  padding-left: 0.15rem;
  padding-right: 0.15rem;
}
</style>
